package _2022.hot100._543_二叉树的直径;

/**
 * @author： YHSimon
 * @date： 2022-06-13 10:37
 */
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
public class Solution {
    private int ans=0;
    public int diameterOfBinaryTree(TreeNode root) {
        if(root==null){
            return 0;
        }
        dfs(root);
        return ans-1;
    }

    // 计算以当前节点为根节点的深度 以及左右子树的高度
    public int dfs(TreeNode node){
        if(node==null){
            return 0;
        }
        int left=dfs(node.left);
        int right=dfs(node.right);
        ans=Math.max(ans, left+right+1);
        return Math.max(left, right)+1;
    }
}
